//
//  CZCommentModel.swift
//  GZWeibo05
//
//  Created by zhangping on 15/11/19.
//  Copyright © 2015年 zhangping. All rights reserved.
//

import UIKit

class CZDetailCommentModel: NSObject {
    
    /// 用于显示正在加载数据cell
    var loading = false
    
    /// 评论的ID
    var id: Int = 0
    
    /// 评论创建时间
    var created_at: String?
    
    /// 评论作者的用户信息字段
    var user: CZUser?
    
    /// 内容
    var text: String?
    
    init(loading: Bool) {
        self.loading = loading
        
        super.init()
    }
    
    /// 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        
        // KVC字典转模型
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                user = CZUser(dict: dict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let properties = ["id", "created_at", "user"]
        
        return "\n\t:评论模型: \(dictionaryWithValuesForKeys(properties))"
    }

    // MARK: - 获取数据
    ///  模型获取数据
    class func loadComment(statusId: Int, since_id: Int, max_id: Int, finished:(comments: [CZDetailCommentModel]?, total_number: Int?, previous_cursor: Int?, next_cursor: Int?, error: NSError?) -> ()) {
        CZNetworkTool.sharedInstance.loadComment(statusId, since_id: since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                print("请求评论失败: \(error)")
                finished(comments: nil, total_number: nil, previous_cursor: nil, next_cursor: nil, error: error)
                return
            }
            
            print("result:\(result)")
            
            // 总数量
            let total_number = result?["total_number"] as? Int
            
            // 上一页id
            let previous_cursor = result?["previous_cursor"] as? Int
            
            // 下一页id
            let next_cursor = result?["next_cursor"] as? Int
            
            // 字典转模型
            var comments = [CZDetailCommentModel]()
            // 解析 comments 里面的评论模型
            if let array = result?["comments"] as? [[String: AnyObject]] {
                for dict in array {
                    let comment = CZDetailCommentModel(dict: dict)
                    
                    comments.append(comment)
                }
                
//                print("微博模型 count: \(comments.count): \(comments)")
                finished(comments: comments, total_number: total_number, previous_cursor: previous_cursor, next_cursor: next_cursor, error: nil)
            } else {
                finished(comments: nil, total_number: total_number, previous_cursor: previous_cursor, next_cursor: next_cursor, error: nil)
            }
        }
    }
}
